package com.sky.controller.admin;

import com.sky.dto.SetmealDTO;
import com.sky.dto.SetmealPageQueryDTO;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.SetmealService;
import com.sky.vo.SetmealVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Api(tags = "套餐相关接口")
@RestController
@RequestMapping("/admin/setmeal")
@Slf4j
public class SetmealController {
    @Autowired
    private SetmealService setmealService;
    @Autowired
    private RedisTemplate redisTemplate;

    //套餐分页查询
    @ApiOperation("套餐分页查询")
    @GetMapping("/page")
    public Result<PageResult> page(SetmealPageQueryDTO dto) {
        log.info("分页查询：{}", dto);
        PageResult pageResult = setmealService.pageQuery(dto);
        return Result.success(pageResult);
    }

    //新增套餐
    //清理指定的缓存数据
    @CacheEvict(value = "setmeal",key = "#dto.categoryId")//删除缓存,根据categoryId删除缓存中对应的数据
    @ApiOperation("新增套餐")
    @PostMapping
    public Result add(@RequestBody SetmealDTO dto) {
        log.info("新增套餐：{}", dto);
        setmealService.addSetmeal(dto);

        return Result.success();
    }
    //回显套餐
    @ApiOperation("回显套餐")
    @GetMapping("/{id}")
    public Result<SetmealVO> getById(@PathVariable Long id) {
        log.info("回显套餐：{}", id);
        SetmealVO setmealVO = setmealService.getById(id);
        return Result.success(setmealVO);
    }
    //修改套餐
    //更新时因为可能设计到多个缓存数据，所以不能通过id删除,可以使用allEntries = true全部删除
    @CacheEvict(value = "setmeal",allEntries = true)//allEntries = true删除所有缓存数据
    @ApiOperation("修改套餐")
    @PutMapping
    public Result update(@RequestBody SetmealDTO dto) {
        log.info("修改套餐：{}", dto);
        setmealService.update(dto);
        return Result.success();
    }
    //批量删除套餐
    //allEntries = true清除setmeal缓存组下的所有数据
    @CacheEvict(value = "setmeal",allEntries = true)//allEntries = true删除所有缓存数据
    @ApiOperation("批量删除套餐")
    @DeleteMapping
    public Result delete(@RequestParam List<Long> ids) {
        log.info("批量删除：{}", ids);
        setmealService.delete(ids);
        return Result.success();
    }
    //起售、停售
    //因为停售、起售操作可能设计到多个缓存数据,可以使用allEntries = true全部删除
    @CacheEvict(value = "setmeal",allEntries = true)//allEntries = true删除所有缓存数据
    @ApiOperation("起售、停售")
    @PostMapping("/status/{status}")
    public Result startOrStop(@PathVariable Integer status, Long id) {
        log.info("起售、停售：{}", status, id);
        setmealService.startOrStop(status, id);
        return Result.success();
    }
}
